<template>
    <a-card>
        <div>
            <a-form layout="horizontal">
                <div class="fold">
                    <a-row>
                        <a-col :md="6" :sm="24">
                            <a-form-item label="库位" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                                <a-input v-model="code" placeholder="请输入" allowClear />
                            </a-form-item>
                        </a-col>
                        <a-col :md="6" :sm="24">
                            <a-form-item label="库位类型" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                                <a-select v-model="rackType">
                                    <a-select-option value="">请选择库位类型</a-select-option>
                                    <a-select-option :value="item.key" v-for="item in typeList" :key="item.key">
                                        {{ item.value }}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </div>
                <span style="float: right; margin-top: 3px">
                    <a-button type="primary" @click="query">查询</a-button>
                    <a-button @click="exportExcel" style="margin-left: 10px" :loading="logging">导出</a-button>
                </span>
            </a-form>
        </div>
        <div>
            <a-space class="operator">
                <a-button @click="showAgvModal('')" type="primary">调度</a-button>
                <a-button @click="showModal(0)" type="primary">新建</a-button>
                <a-button @click="batchDel">批量删除</a-button>
                <a-button @click="excelImport">导入</a-button>

                <a-modal :visible="visible" title="编辑" @ok="handleOk" @cancel="handleCancel" width="800px">
                    <a-form :form="form">
                        <a-form-item :label="$t('id')" v-show="false">
                            <a-input name="id" id="id" v-model="model.Id" v-show="false" />
                        </a-form-item>
                        <a-row>
                            <a-col :span="24">
                                <a-form-item :label-col="layout.labelCol" :wrapper-col="layout.wrapperCol" label="编码">
                                    <a-input v-model="model.Code" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row>
                            <a-col :span="24">
                                <a-form-item :label-col="layout.labelCol" :wrapper-col="layout.wrapperCol" label="库位类型">
                                    <a-select v-model="model.Type">
                                        <a-select-option value="">请选择库位类型</a-select-option>
                                        <a-select-option :value="item.key" v-for="item in typeList" :key="item.key">
                                            {{ item.value }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row>
                            <a-col :span="24">
                                <a-form-item :label-col="layout.labelCol" :wrapper-col="layout.wrapperCol" label="库位状态">
                                    <a-select v-model="model.Status">
                                        <a-select-option value="">请选择库位类型</a-select-option>
                                        <a-select-option :value="item.key" v-for="item in statusList" :key="item.key">
                                            {{ item.value }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row>
                            <a-col :span="24">
                                <a-form-item :label-col="layout.labelCol" :wrapper-col="layout.wrapperCol" label="货架类型">
                                    <a-select v-model="model.PodCode">
                                        <a-select-option value="">请选择货架类型</a-select-option>
                                        <a-select-option value="工装_7寸">工装_7寸</a-select-option>
                                        <a-select-option value="工装_13寸">工装_13寸</a-select-option>
                                        <a-select-option value="料箱">料箱</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row>
                            <a-col :span="24">
                                <a-form-item :label-col="layout.labelCol" :wrapper-col="layout.wrapperCol" label="备注">
                                    <a-input v-model="model.Remark" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-modal>

                <a-modal :visible="visibleAgv" title="Agv调度" @ok="agvRun" @cancel="handleCancel" width="800px">
                    <a-form :form="form">
                        <a-row>
                            <a-col :span="24">
                                <a-form-item :label-col="layout.labelCol" :wrapper-col="layout.wrapperCol" label="起点">
                                    <a-select v-model="agvFrom" @change="changeAgv">
                                        <a-select-option value="">请选择起点</a-select-option>
                                        <a-select-option :value="item.Code" v-for="item in agvFromData" :key="item.Id">
                                            {{ typeList.find(i => i.key == item.Type).value
                                                + "（" + item.Code + "）"
                                                + "（" + item.PodCode + "）" }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row>
                            <a-col :span="24">
                                <a-form-item :label-col="layout.labelCol" :wrapper-col="layout.wrapperCol" label="终点">
                                    <a-select v-model="agvTo">
                                        <a-select-option value="">请选择终点</a-select-option>
                                        <a-select-option :value="item.Code" v-for="item in agvToData" :key="item.Id">
                                            {{ typeList.find(i => i.key == item.Type).value + "（" + item.Code + "）" }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-modal>
                <drawer v-if="visibleImport" placement="top" v-model="visibleImport">
                    <div class="side-setting">
                        <div class="panel-body">
                            <div style="display:flex">
                                <span class="badge ant-btn-primary">1</span>
                                <div class="text">下载导入模板，批量填写库位信息</div>
                                <a-button @click="downExcel">下载</a-button>
                            </div>
                            <div class="line"></div>
                            <div style="display:flex;">
                                <span class="badge ant-btn-primary">2</span>
                                <div class="text">上传填写好的库位信息</div>
                                <a-upload name="file" :showUploadList="false" accept=".xlsx, .xls"
                                    :customRequest="fileUpload">
                                    <a-button type="success">选择文件</a-button>
                                </a-upload>
                                <div class="fileName" v-if="file">{{ file.name }}</div>
                            </div>
                            <div style="padding-top:70px;text-align:center">
                                <a-button type="primary" @click="importData">导入</a-button>
                            </div>
                        </div>
                    </div>
                </drawer>
            </a-space>
            <a-table :columns="columns" :dataSource="dataSource" :pagination="pagination"
                :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                :rowKey="(dataSource) => dataSource.Id">
                <template slot="time" slot-scope="text,record">
                    {{ (record.UpdateTime ? record.UpdateTime : record.CreateTime) | dateTimeFormat }}
                </template>
                <template slot="status" slot-scope="text">
                    <a-tag :color="text == 0 ? 'green' : text == 1 ? 'red' : 'geekblue'">
                        {{ statusList.find(i => i.key == text).value }}
                    </a-tag>
                </template>
                <template slot="type" slot-scope="text">
                    {{ typeList.find(i => i.key == text).value }}
                </template>
                <div slot="action" slot-scope="text, record">
                    <a @click="showAgvModal(record.Code)" v-if="record.Status == 1">
                        <a-icon type="setting" />调度
                    </a>
                    <a @click="showModal(record.Id)">
                        <a-icon type="edit" />
                        编辑
                    </a>
                    <a-popconfirm title="是否删除" @confirm="remove(record.Id)">
                        <a>
                            <a-icon type="delete" />删除
                        </a>
                    </a-popconfirm>
                </div>
            </a-table>
        </div>
    </a-card>
</template>

<script>
import { agvPointMapService, agvServoce } from '/src/services'
import moment from 'moment'
import ExportJsonExcel from "js-export-excel"
import Drawer from '../../components/tool/Drawer'
import * as xlsx from 'xlsx'

const columns = [
    {
        title: '序号',
        width: 60,
        customRender: (text, record, index) => `${index + 1}`,
    },
    {
        title: '编码',
        dataIndex: 'Code'
    },
    {
        title: '库位类型',
        dataIndex: 'Type',
        scopedSlots: { customRender: 'type' }
    },
    {
        title: '库位状态',
        dataIndex: 'Status',
        scopedSlots: { customRender: 'status' }
    },
    {
        title: '货架类型',
        dataIndex: 'PodCode'
    },
    {
        title: '备注',
        dataIndex: 'Remark',
    },
    {
        title: '操作',
        scopedSlots: { customRender: 'action' }
    }
]

export default {
    name: 'warehouseWarn',
    filters: {
        dateTimeFormat(val) {
            if (val == null) return ''
            return val.substring(0, 10)
        }
    },
    components: { Drawer },
    data() {
        return {
            advanced: false,
            columns: columns,
            dataSource: [],
            visible: false,
            visibleAgv: false,
            visibleImport: false,
            layout: {
                labelCol: { span: 6 },
                wrapperCol: { span: 16 }
            },
            form: this.$form.createForm(this),
            model: {},
            code: '',
            rackType: '',
            typeList: [
                { key: 0, value: '全自动贴标机' },
                // { key: 1, value: '半自动贴标机' },
                { key: 2, value: '智能货柜' },
                { key: 3, value: '湿敏仓_入库' },
                { key: 4, value: '湿敏仓_出库' },
                { key: 5, value: '点料机_入料口' },
                { key: 6, value: '点料机_出料口' },
                { key: 7, value: '退料区' },
                { key: 8, value: '收料区' },
                { key: 9, value: '发料区' },
                { key: 10, value: '临时' }
            ],
            statusList: [
                { key: 0, value: '空闲' },
                { key: 1, value: '占用' },
                { key: 2, value: '出任务' },
                { key: 3, value: '入任务' },
            ],
            pagination: {
                total: 0,
                current: 1,
                pageSize: 20,
                showTotal: (total) => `总计 ${total} 条`,
                onChange: (current, pageSize) => {
                    this.pagination.pageSize = pageSize
                    this.pagination.current = current
                    this.loadData()
                }
            },
            selectedRowKeys: [],
            logging: false,
            file: {},
            uploadData: [],
            agvData: [],
            agvFromData: [],
            agvToData: [],
            agvFrom: '',
            agvTo: '',

        }
    },
    mounted: function () {
        this.loadData()
    },
    methods: {
        changesx(value) {
            this.model.Status = value ? 0 : 1
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys;
        },
        async batchDel() {
            if (this.selectedRowKeys.length === 0) {
                this.$message.error("请勾选至少一条数据", 3)
            }
            let result = await agvPointMapService.batchDel(this.selectedRowKeys.join(','))
            if (result && result.data) {
                if (result.data.Success) {
                    this.$message.success("删除成功", 3)
                    this.loadData()
                } else {
                    this.$message.error(result.data.Message, 3)
                }
            }
        },
        downExcel() {
            var option = {};
            var sheetFilter = [];
            var sheetHeader = [];
            columns.forEach(item => {
                if (item.title !== "序号" && item.title !== "操作") {
                    sheetFilter.push(item.dataIndex)
                    sheetHeader.push(item.title)
                }
            })
            option.fileName = this.$route.name + '_导入模板';
            option.datas = [];
            option.datas = [
                {
                    sheetData: [],
                    sheetName: 'sheet',
                    sheetFilter: sheetFilter,
                    sheetHeader: sheetHeader,
                }
            ];
            var toExcel = new ExportJsonExcel(option);
            toExcel.saveExcel();
        },
        async fileUpload(info) {
            let file = info.file;//info是组件为你解析好的数据
            if (!file) return;
            this.file = file;
            let reader = await this.upload();
            const worker = xlsx.read(reader, { type: 'binary' });


            let arr = [];

            let temp = xlsx.utils.sheet_to_json(worker.Sheets[worker.SheetNames[0]]);
            temp.forEach((item) => {
                var data = {}
                console.log(item)
                Object.keys(item).forEach((el) => {
                    var value = String(item[el]);
                    switch (el) {
                        case "编码":
                            data.Code = value;
                            break;
                        case "货架编码":
                            data.PodCode = value;
                            break;
                        case "库位类型":
                            var type = this.typeList.find(item => item.value == value);
                            data.Type = type ? type.key : 0;
                            break;
                        case "库位状态":
                            var status = this.statusList.find(item => item.value == value);
                            data.Status = status ? type.key : 0;
                            break;
                        case "备注":
                            data.Remark = value;
                            break;
                        default:
                            break;
                    }
                });
                if (data.PodCode == null) {
                    data.PodCode = ''
                }
                if (data.Remark == null) {
                    data.Remark = ''
                }
                if (data.Code) {
                    arr.push(data)
                }
            });
            this.uploadData = arr
            info.file.status = 'done';
            info.onSuccess();
            if (arr.length == 0) {
                this.$message.error('请上传正确的模板')
                this.file = {}
                return
            }
        },
        async upload() {
            return new Promise(resolve => {
                let reader = new FileReader()
                reader.readAsBinaryString(this.file);//读取文件的原始二进制数据
                reader.onload = ev => {
                    resolve(ev.target.result)
                }
            })
        },
        async importData() {
            var result = await agvPointMapService.batchAdd(this.uploadData)
            if (result && result.data) {
                this.$message.success('导入成功')
                this.visibleImport = false
                this.loadData()
            } else if (result.data == 0) {
                this.$message.error('导入失败，请联系管理员')
            }
        },
        async loadData() {
            this.dataSource = []
            var result = await agvPointMapService.getData(this.code, this.rackType, this.pagination.pageSize, this.pagination.current)
            if (result && result.data) {
                this.dataSource = result.data.data
                this.pagination.total = result.data.total
            }
        },
        query() {
            this.pagination.current = 1
            this.loadData()
        },
        async showModal(id) {
            this.visible = true
            if (id !== 0) {
                this.id = id
                let model = await agvPointMapService.detail(id)
                this.model = model.data
            } else {
                this.model = { Id: 0, Type: '', PodCode: '', Remark: '', Status: 0 }
            }
        },
        changeAgv() {
            var agv = this.agvData.find(i => i.Code == this.agvFrom)
            if (agv) {
                // { key: 0, value: '全自动贴标机' },
                // { key: 1, value: '半自动贴标机' },
                // { key: 2, value: '智能货柜' },
                // { key: 3, value: '湿敏仓_入库' },
                // { key: 4, value: '湿敏仓_出库' },
                // { key: 5, value: '点料机_入料口' },
                // { key: 6, value: '点料机_出料口' },
                // { key: 7, value: '退料区' },
                // { key: 8, value: '收料区' },
                // { key: 9, value: '发料区' },
                // { key: 10, value: '临时' }
                switch (agv.Type) {
                    case 0://全自动贴标机
                        this.agvToData = this.agvData.filter(i => i.Status == 0 && (i.Type == 8 || i.Type == 10))
                        break;
                    case 1://半自动贴标机
                        this.agvToData = this.agvData.filter(i => i.Status == 0 && i.Type == 3)
                        break;
                    case 2://智能货柜
                        this.agvToData = this.agvData.filter(i => i.Status == 0 && i.Type == 9)
                        break;
                    case 3://湿敏仓_入库
                        this.agvToData = this.agvData.filter(i => i.Status == 0 &&  (i.Type == 8 || i.Type == 10))
                        break;
                    case 4://湿敏仓_出库
                        this.agvToData = this.agvData.filter(i => i.Status == 0 && i.Type == 9)
                        break;
                    case 5://点料机_入料口
                        this.agvToData = this.agvData.filter(i => i.Status == 0 && (i.Type == 8 || i.Type == 10))
                        break;
                    case 6://点料机_出料口
                        if (agv.PodCode == '工装_7寸') {
                            this.agvToData = this.agvData.filter(i => i.Status == 0 && (i.Type == 0))
                        } else {
                            this.agvToData = this.agvData.filter(i => i.Status == 0 && (i.Type == 3))
                        }
                        break;
                    case 7://退料区
                        this.agvToData = this.agvData.filter(i => i.Status == 0 && i.Type == 8)
                        break;
                    case 8://收料区
                        this.agvToData = this.agvData.filter(i => i.Status == 0 && (i.Type == 0 || i.Type == 1 || i.Type == 5 || i.Type == 10))
                        break;
                    case 9://发料区
                        this.agvToData = this.agvData.filter(i => i.Status == 0 && i.Type == 10)
                        break;
                    default:
                        this.agvToData = this.agvData.filter(i => i.Status == 0)
                        break;
                }
            }
        },
        async showAgvModal(from = '') {
            this.visibleAgv = true
            this.agvFrom = ''
            this.agvTo = ''
            let result = await agvPointMapService.getAll()
            if (result && result.data) {
                this.agvData = result.data
                this.agvFromData = result.data.filter(i => i.Status == 1)
                this.agvToData = result.data.filter(i => i.Status == 0)
                // this.pagination.total = result.data.total
                console.log(from)
                if (from) {
                    this.agvFrom = from
                    this.changeAgv()
                }
            }
        },
        async agvRun() {
            if (!this.agvFrom) {
                this.$message.error('请选择起点！')
                return;
            }
            if (!this.agvTo) {
                this.$message.error('请选择终点！')
                return;
            }
            let result = await agvServoce.run(this.agvFrom, this.agvTo)
            if (result && result.data) {
                if (result.data.Code == 0) {
                    this.$message.success('调度成功')
                    this.visibleAgv = false
                    this.loadData()
                } else {
                    this.$message.error(result.data.Message)
                }
            }
        },

        handleOk() {
            if (!this.model.Code) {
                this.$message.error('请输入库位编码！')
                return;
            }
            if (this.model.Type === "") {
                this.$message.error('请选择库位类型！')
                return;
            }
            this.form.validateFields((err) => {
                if (!err) {
                    agvPointMapService.save(this.model).then(this.afterUpdateEvent)
                }
            })
        },
        async afterUpdateEvent(res) {
            if (res.data) {
                this.$message.success('保存成功')
                this.visible = false
                this.loadData()
            } else {
                this.$message.error('保存失败')
            }
        },
        handleCancel() {
            this.visible = false
            this.visibleAgv = false
        },
        async remove(id) {
            let result = await agvPointMapService.remove(id)
            if (result.data) {
                this.$message.success("删除成功", 3)
                this.loadData()
            }
        },
        async exportExcel() {
            this.logging = true;
            var result = await agvPointMapService.getData(this.code, this.rackType, 10000, 1)

            if (result && result.data) {
                var option = {};
                let dataTable = [];
                let datas = result.data.data;

                datas.forEach(item => {
                    item.CreateTime = (item.UpdateTime ? item.UpdateTime : item.CreateTime).replace('T', ' ').substring(0, 19)
                    item.Type = this.typeList.find(i => i.key == item.Type).value;
                    item.Status = this.statusList.find(p => p.key == item.Status).value;
                    dataTable.push(item);
                });
                var sheetFilter = [];
                var sheetHeader = [];
                columns.forEach(item => {
                    if (item.title !== "序号" && item.title !== "操作") {
                        sheetFilter.push(item.dataIndex)
                        sheetHeader.push(item.title)
                    }
                })
                option.fileName = this.$route.name + '_' + moment().format('YYYY-MM-DD');
                option.datas = [
                    {
                        sheetData: dataTable,
                        sheetName: 'sheet',
                        sheetFilter: sheetFilter,
                        sheetHeader: sheetHeader,
                    }
                ];
                var toExcel = new ExportJsonExcel(option);
                toExcel.saveExcel();
                this.logging = false;
            }

        },
        excelImport() {
            this.visibleImport = true
            this.file = {}
            this.uploadData = []
        }
    }
}
</script>

<style lang="less" scoped>
.search {
    margin-bottom: 54px;
}

.fold {
    width: calc(100% - 216px);
    display: inline-block;
}

.operator {
    margin-bottom: 18px;
}

@media screen and (max-width: 900px) {
    .fold {
        width: 100%;
    }
}


.side-setting {
    background-color: @base-bg-color;
    padding: 24px;
    position: relative;

    .badge {
        padding: 7px;
        width: 30px;
        border-radius: 10px;
        display: inline-block;
        text-align: center;
    }

    .line {
        margin: 10px 13px;
        border-left: 2px dashed #999;
        height: 40px;
    }

    .text {
        padding: 5px;
        font-size: 16px;
        margin-right: 5px;
    }

    .fileName {
        padding: 5px;
        margin-left: 15px;
    }

    .panel-body {
        padding: 50px 100px;
        border: 1px solid #BFBFBF;
    }
}
</style>
